package com.anytron.utils;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.anytron.model.AppApollo;
import com.anytron.model.AppConfigs;
import com.anytron.model.res.NameSpaceContent;
import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * 开放平台连接apollo获取相关配置
 * 
 * @author anytron
 *
 */
@Slf4j
@Component
public class ApolloServiceUtils {

	private static final String CONTENT = "content";

	public ApolloOpenApiClient getOpenApiClient(AppApollo appApollo) {
		return ApolloOpenApiClient.newBuilder().withPortalUrl(appApollo.getApolloPortalUrl())
				.withToken(appApollo.getApolloToken()).build();
	}

	public List<String> getNameSpacesByConfig(AppApollo appApollo) {
		ApolloOpenApiClient client = getOpenApiClient(appApollo);
		List<OpenNamespaceDTO> namespaces = client.getNamespaces(appApollo.getApolloAppId(), appApollo.getApolloEnv(),
				appApollo.getApolloCluster());
		return namespaces.stream().map(item -> {
			return item.getNamespaceName();
		}).collect(Collectors.toList());
	}

	/**
	 * 通过应用的所有配置获取对应的命名空间配置内容
	 * 
	 * @param appApollo
	 * @param appConfigs
	 * @return
	 */
	public List<NameSpaceContent> getContentByAppConfigs(AppApollo appApollo, List<AppConfigs> appConfigs) {
		ApolloOpenApiClient client = getOpenApiClient(appApollo);
		return appConfigs.stream().map(item -> {
			String configName = item.getConfigName();
			String apolloNamespace = item.getApolloNamespace();
			OpenItemDTO openItemDTO = client.getItem(appApollo.getApolloAppId(), appApollo.getApolloEnv(),
					appApollo.getApolloCluster(), apolloNamespace, CONTENT);
			NameSpaceContent nsc = new NameSpaceContent();
			nsc.setPin(appApollo.getApolloAppId() + "#" + appApollo.getApolloEnv() + "#" + appApollo.getApolloCluster()
					+ "#" + apolloNamespace);
			nsc.setConfigName(configName);
			nsc.setNameSpace(apolloNamespace);
			nsc.setPath(item.getConfigPath());
			if (openItemDTO != null) {
				String value = openItemDTO.getValue();
				if ("".equals(value.trim())) {
					log.info("[" + apolloNamespace + "] 配置无效,不再适配");
				}
				nsc.setContent(value);
			} else {
				log.info("[" + apolloNamespace + "] 不存在");
			}
			return nsc;
		}).filter(item -> StringUtils.isNotBlank(item.getContent())).collect(Collectors.toList());
	}

}
